import java.util.concurrent.CountDownLatch;

public class Communication implements Runnable {
	private Client client;
	private Message msg;
	private ClientUi ui;
	private final CountDownLatch sendEnd;

	public Communication(ClientUi UI, Client client, Message msg) {
		this.client = client;
		this.msg = msg;
		this.ui = UI;
		this.sendEnd = ui.sendEnd;
	}

	/**
	 * Function to send a message and waiting for the receiving message
	 * 
	 * @return message receive from the server to answer our message
	 */
	public synchronized Message request() {
		// we first send the message
		client.sendMsg(msg);
		if (msg.getType() == Message.STOP_GAME) {
			sendEnd.countDown();
			return null;
		}
		// we receive a message from the server
		Message receivedMsg = client.readMsg();
		return receivedMsg;
	}

	@Override
	public void run() {
		Message receivedMsg = request();
		if (receivedMsg != null) {
			processMsg(receivedMsg);
		}
	}

	/**
	 * Function to do the process after receiving a message Look for the type of
	 * the message and change the variable of the UI
	 * 
	 * @param msg
	 *            : message to process
	 */
	public void processMsg(Message msg) {
		System.out.print("Message receive: " + msg + "\n\n");
		switch (msg.getType()) {
		case Message.UNDEF:
			ui.labError.setText("Error : receive undefined message");
			break;
		case Message.SERVER_CLIENT:
			ui.chainWord.setText(msg.getArg());
			ui.failLeft.setText("You still have "
					+ Integer.toString(msg.getAttemptLeft())
					+ " attempt(s) left");
			break;
		case Message.ERROR:
			ui.labError.setText(msg.getArg());
			break;
		case Message.GAME_WON:
			ui.labWin
					.setText("You win, you can try to guess a new word by going to edit/start menu");
			ui.chainWord.setText(msg.getArg());
			ui.labScore.setText("Score: " + Integer.toString(msg.getScore()));
			ui.btnSend.setEnabled(false);
			ui.start = false;
			break;
		case Message.GAME_LOST:
			ui.labWin
					.setText("You lost, you can try to guess a new word by going to edit/start menu");
			ui.chainWord.setText(msg.getArg());
			ui.labScore.setText("Score: " + Integer.toString(msg.getScore()));
			ui.failLeft.setText("You have "
					+ Integer.toString(msg.getAttemptLeft()) + " attempt left");
			ui.btnSend.setEnabled(false);
			ui.start = false;
			break;
		}
	}

}
